import redis.clients.jedis.Jedis;

/**
 * Takes a website and its contents
 * Creates a database linking from content to relevant websites
 * 
 * @author Elizabeth Mahon and Lisa Park
 */
public class Indexer {
	
	/**
	 * Adds a website to the database
	 * Takes the url (as a string) and the string contents of the website
	 * Turns the contents into a list of words
	 * Links each word to relevant websites and puts it in the database
	 * 
	 * @param url
	 * @param contents
	 */
	public void add(String url, String contents){

		System.out.println(url);
		String [] contentArray;
		contentArray = breakContentIntoWords(contents);
		storeInDatabase(url, contentArray);
	}
	
	/**
	 * @param String contents
	 * @return contents broken into an array
	 */
	public String[] breakContentIntoWords(String contents){
		String[] contentArray;
		contentArray = contents.split(" ");
		return contentArray;
	}
	
	/**
	 * Take a url and an array of words on the page
	 * Add a word-url pair to the database.
	 * @param url
	 * @param contentArray
	 */
	
	public void storeInDatabase(String url, String[] contentArray){
	//creating Database
		 String host = "dory.redistogo.com";
		 String auth = "7fa37f7a9619abc89929da2ebecf5114";
		 int port = 10665;
		 Jedis jedis = new Jedis(host, port);
		 jedis.auth(auth);
	
		 //loop through contentArray and set each word as key
		 // with url as value in the database.
		 for (String word: contentArray){
			 if(!jedis.lrange(word, 0, -1).contains(url))
			 {
				 jedis.rpush(word, url);
			 }
			 System.out.println(word + " ......... " + jedis.lrange(word, 0, -1));
		 }
		 
		 jedis.quit();
	}
}